import { ServerOptions } from 'vite'
import dayjs from 'dayjs'

type EnvNumberType = 1 | 2 | 3 | 4
type EnvType = 'dev' | 'test' | 'pre' | 'prod'
type VersionInfo = { envName: string, versionName: string, version: string, updateDate: string }

// 环境 map
const envMap: { [key in EnvNumberType]: EnvType } = {
  1: 'dev',
  2: 'test',
  3: 'pre',
  4: 'prod',
}

// 版本信息
const versionMap: { [key in EnvType]: VersionInfo } = {
  dev: {
    envName: '内网开发环境',
    versionName: 'C5-H5 dev',
    version: '1.0.1',
    updateDate: dayjs().format('YYYY-MM-DD'),
  },
  test: {
    envName: '外网测试环境',
    versionName: 'C5-H5 test',
    version: '1.0.1',
    updateDate: dayjs().format('YYYY-MM-DD'),
  },
  pre: {
    envName: '外网预发环境',
    versionName: 'C5-H5 pre',
    version: '1.0.1',
    updateDate: dayjs().format('YYYY-MM-DD'),
  },
  prod: {
    envName: '生产环境',
    versionName: 'C5-H5 Product',
    version: '1.0.1',
    updateDate: dayjs().format('YYYY-MM-DD'),
  },
}

// 代理配置
const serverMap: { [key in EnvType]: ServerOptions } = {
  dev: {
    host: '127.0.0.1',
    port: 7060,
    proxy: {
      '/api': {
        target: 'http://192.168.3.6:8000',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, 'api')
      }
    },
  },
  test: {
    host: '127.0.0.1',
    port: 7060,
    proxy: {
      '/api': {
        target: 'http://192.168.3.9:8000',
        // target: 'http://192.168.3.31:8000',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, 'api')
      },
      '/wxapi': {
        target: 'https://qyapi.weixin.qq.com',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/wxapi/, '')
      }
    },
  },
  pre: {
    host: '127.0.0.1',
    port: 7060,
    proxy: {
      '/api': {
        target: 'http://192.168.3.6:8000',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, 'api')
      }
    },
  },
  prod: {
    host: '127.0.0.1',
    port: 7060,
    proxy: {
      '/api': {
        target: 'http://192.168.3.31:8000',
        changeOrigin: true,
        rewrite: (path: string) => path.replace(/^\/api/, 'api')
      },
      '/wxapi': {
        target: 'https://qyapi.weixin.qq.com',
        changeOrigin: true,
        rewrite: (path: string) => path.replace(/^\/wxapi/, '')
      }
    },
  },
}

// file base url
const fileBaseUrlMap: { [key in EnvType]: string } = {
  dev: '/',
  test: '/',
  pre: '/',
  prod: '/',
}

const getEnvironmentConfig = (envNumber: EnvNumberType): {
  serverConfig: ServerOptions
  versionInfo: VersionInfo
  fileBaseUrl: string
} => {
  let envName = envMap[envNumber]
  return {
    serverConfig: serverMap[envName],
    versionInfo: versionMap[envName],
    fileBaseUrl: fileBaseUrlMap[envName],
  }
}

export default getEnvironmentConfig(1)
